﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using YSC_Core.BLL.Domain.CommonModels;
using YSC_Core.BLL.Domain.Entity;
using YSC_Core.BLL.Domain.Utils;
using YSC_Core.BLL.Domain.ViewModels;
using YSC_Core.BLL.Repository;
using YSC_OpenPlatform_API.Entity;
using YSC_Services.BLL.Services.Interfaces;

namespace YSC_Services.BLL.Services.Implementations
{
    /// <summary>
    /// 鱼价接口实现
    /// </summary>
    public class MarketPriceAppServices : IMarketPriceAppServices
    {
        private IEfRepository _rep;

        public MarketPriceAppServices(IEfRepository rep)
        {
            this._rep = rep;
        }

        /// <summary>
        /// 鱼价列表
        /// </summary>
        /// <param name="index">页码</param>
        /// <param name="size">数量</param>
        /// <param name="priceType">报价类型0:市场价 1：产地价</param>
        /// <param name="areaName">地区名称</param>
        /// <param name="fishType">鱼种类别</param>
        /// <param name="fishName">鱼种名称</param>
        /// <param name="datetime">时间</param>
        /// <param name="areaId">区县Id</param>
        /// <returns></returns>
        public ReturnValueModel GetMarketPriceAll(int index, int size, int priceType, string datetime, string areaName, string fishType, string fishName, string areaId)
        {

            if (!string.IsNullOrEmpty(areaName) && !string.IsNullOrEmpty(areaId))
                return new ReturnValueModel { Code = 400, Msg = "areaId AND areaName 重复" };


            //string url = "https://testopen.95155.com/save/apis/login/";
            //string dateStr = string.Format("user=admin&pwd=123456&cid=123x3rr4");
            // Util.SetCertificatePolicy();
            //var itemWX = HttpUtils.HttpPost(url, dateStr);

            // var MarketPriceAll = _rep.Where<MarketPrice>(p => p.Status == 0).Take(10).ToSql();

            if (priceType == 0)
            {
                //start
                Stopwatch watchM = Stopwatch.StartNew();
                var fingerAllM = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

                var startDateM = string.IsNullOrEmpty(datetime) ? DateTime.Now : Convert.ToDateTime(datetime);
                var sqlM = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE Areaname={0} UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAllM = _rep.SqlQuery<Area>(sqlM, string.IsNullOrEmpty(areaName) ? "上海市" : areaName).Select(p => new Area { YunCode = p.YunCode }).ToList();

                List<string> arrtM = new List<string>();
                foreach (var item in areaAllM)
                    arrtM.Add(item.YunCode);
                string[] arrt2M = arrtM.ToArray();


                var marketUnitList = from m in _rep.Where<MarketUnit>(p => p.Status == 0)
                                     join r in _rep.Where<Area>(p => p.Status == 0) on m.AreaUnCode equals r.YunCode
                                     where !string.IsNullOrEmpty(areaId) ? r.YunCode == areaId : arrt2M.Contains(r.YunCode)
                                     select new { m.Id };

                List<string> marketUnit = new List<string>();
                foreach (var item in marketUnitList.ToList())
                    marketUnit.Add(item.Id);

                string[] marketUnits = marketUnit.ToArray();


                var MarketPriceAll = from a in _rep.Where<MarketPrice>(p => p.Status == 0)
                                     where a.CreateTime >= startDateM.AddMonths(-3) && a.CreateTime <= startDateM && marketUnits.Contains(a.MarketId)
                                     join m in _rep.Where<MarketUnit>(p => p.Status == 0) on a.MarketId equals m.Id
                                     //join r in _rep.Where<Area>(p => p.Status == 0) on m.AreaUnCode equals r.YunCode
                                     //where !string.IsNullOrEmpty(areaId) ? r.YunCode == areaId : arrt2M.Contains(r.YunCode)
                                     // join y in _rep.Where<YscUser>(p => p.Status == 0) on a.UserId equals y.Id
                                     join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId equals f.FishCode
                                     join d in _rep.Where<Dictionary>(p => p.Status == 0) on f.Type equals d.Id
                                     select new
                                     {
                                         a.Id,
                                         f.FishName,
                                         fishType = d.Name,
                                         // y.UserName,
                                         a.UserId,
                                         m.Address,
                                         a.AveragePrice,
                                         a.CreateTime
                                     };


                var modelM = MarketPriceAll.OrderByDescending(p => p.CreateTime)
                        .WhereIf(p => p.FishName == fishName, string.IsNullOrEmpty(fishName) == false)
                        .WhereIf(p => p.fishType == fishType, string.IsNullOrEmpty(fishType) == false)
                        .ToPaginationList(index, size)
                        .ToList().Join(_rep.Where<YscUser>(p => p.Status == 0), a => a.UserId, y => y.Id, (a, y) => new { a.Id, a.FishName, UserName = System.Web.HttpUtility.UrlDecode(y.UserName, Encoding.UTF8), a.Address, a.AveragePrice, a.CreateTime, a.UserId }).ToList();





                watchM.Stop();
                Stopwatch watch1M = Stopwatch.StartNew();

                List<string> arrtIdsM = new List<string>();
                foreach (var item in modelM)
                    arrtIdsM.Add(item.Id);
                string[] arrtIdM = arrtIdsM.ToArray();

                var marketPricesAllM = from a in _rep.Where<MarketPrices>(p => p.Status == 0)
                                       where a.CreateTime >= startDateM.AddMonths(-3) && a.CreateTime <= startDateM && arrtIdM.Contains(a.MarketPriceId)
                                       join f in _rep.Where<FishSpecies>(s => s.Status == 0) on a.DescriptionId.Trim() equals f.FishCode
                                       select new MarketPricesModel
                                       {
                                           MarketPriceId = a.MarketPriceId,
                                           Description = f.Description.Trim(),
                                           Price = a.Price
                                       };

                var marketPricessqlM = marketPricesAllM.ToSql();

                var marketPricesListM = marketPricesAllM.ToList();



                var modelsM = modelM
                .Select(p => new MarketPriceModel
                {
                    Id = p.Id,
                    FishName = p.FishName,
                    UserId = p.UserId,
                    UserName = p.UserName,
                    AveragePrice = p.AveragePrice,
                    UnitAddress = p.Address,
                    CreateTime = p.CreateTime,
                    MarketPricesModel = marketPricesListM.Where(a => a.MarketPriceId == p.Id).DistinctBy(a => new { Description = a.Description.Trim() }).ToList()
                });

                watch1M.Stop();


                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = modelsM, Timer = watchM.ElapsedMilliseconds, Timer1 = watch1M.ElapsedMilliseconds } };
            }

            Stopwatch watch = Stopwatch.StartNew();
            var fingerAll = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

            var startDate = string.IsNullOrEmpty(datetime) ? DateTime.Now : Convert.ToDateTime(datetime);
            var sql = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE Areaname={0} UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
            var areaAll = _rep.SqlQuery<Area>(sql, string.IsNullOrEmpty(areaName) ? "上海市" : areaName).Select(p => new Area { YunCode = p.YunCode }).ToList();

            List<string> arrt = new List<string>();
            foreach (var item in areaAll)
                arrt.Add(item.YunCode);
            string[] arrt2 = arrt.ToArray();

            var PlaceOfOriginPriceAll = from a in _rep.Where<PlaceOfOriginPrice>(p => p.Status == 0)
                                        where a.CreateTime >= startDate.AddMonths(-1) && a.CreateTime <= startDate
                                        join m in _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0) on a.PlaceOfOriginId equals m.Id
                                        join r in _rep.Where<Area>(p => p.Status == 0) on m.AreaUnCode equals r.YunCode
                                        where string.IsNullOrEmpty(areaName) && string.IsNullOrEmpty(areaId) ? a.Status == 0 : !string.IsNullOrEmpty(areaId) ? r.YunCode == areaId : arrt2.Contains(r.YunCode)
                                        // join y in _rep.Where<YscUser>(p => p.Status == 0) on a.UserId equals y.Id
                                        join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId equals f.FishCode
                                        join d in _rep.Where<Dictionary>(p => p.Status == 0) on f.Type equals d.Id
                                        select new
                                        {
                                            a.Id,
                                            f.FishName,
                                            fishType = d.Name,
                                            // y.UserName,
                                            a.UserId,
                                            m.Address,
                                            a.AveragePrice,
                                            a.CreateTime
                                        };


            var model = PlaceOfOriginPriceAll.OrderByDescending(p => p.CreateTime)
                    .WhereIf(p => p.FishName == fishName, string.IsNullOrEmpty(fishName) == false)
                    .WhereIf(p => p.fishType == fishType, string.IsNullOrEmpty(fishType) == false)
                    .ToPaginationList(index, size)
                    .ToList().Join(_rep.Where<YscUser>(p => p.Status == 0), a => a.UserId, y => y.Id, (a, y) => new { a.Id, a.FishName, UserName = System.Web.HttpUtility.UrlDecode(y.UserName, Encoding.UTF8), a.Address, a.AveragePrice, a.CreateTime, a.UserId }).ToList();





            watch.Stop();
            Stopwatch watch1 = Stopwatch.StartNew();

            List<string> arrtIds = new List<string>();
            foreach (var item in model)
                arrtIds.Add(item.Id);
            string[] arrtId = arrtIds.ToArray();

            var marketPricesAll = from a in _rep.Where<PlaceOfOriginPrices>(p => arrtId.Contains(p.PlaceOfOriginPriceId))
                                  join f in _rep.Where<FishSpecies>(s => s.Status == 0) on a.DescriptionId.Trim() equals f.FishCode
                                  select new MarketPricesModel
                                  {
                                      MarketPriceId = a.PlaceOfOriginPriceId,
                                      Description = f.Description.Trim(),
                                      Price = a.Price
                                  };

            var marketPricessql = marketPricesAll.ToSql();

            var marketPricesList = marketPricesAll.ToList();



            var models = model
            .Select(p => new MarketPriceModel
            {
                Id = p.Id,
                FishName = p.FishName,
                UserId = p.UserId,
                UserName = p.UserName,
                AveragePrice = p.AveragePrice,
                UnitAddress = p.Address,
                CreateTime = p.CreateTime,
                MarketPricesModel = marketPricesList.Where(a => a.MarketPriceId == p.Id).DistinctBy(a => new { Description = a.Description.Trim() }).ToList()
            });

            watch1.Stop();


            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = models, Timer = watch.ElapsedMilliseconds, Timer1 = watch1.ElapsedMilliseconds } };

        }

        /// <summary>
        /// 塘口鱼价列表
        /// </summary>
        /// <param name="index">页码</param>
        /// <param name="size">数量</param>
        /// <param name="areaName">地区名称</param>
        /// <param name="fishType">鱼种类别</param>
        /// <param name="fishName">鱼种名称</param>
        /// <param name="datetime">时间</param>
        /// <param name="areaId">区县Id</param>
        /// <returns></returns>
        public ReturnValueModel GetPlaceOfOriginPriceAll(int index, int size, string datetime, string areaName, string fishType, string fishName, string areaId)
        {
            if (!string.IsNullOrEmpty(areaName) && !string.IsNullOrEmpty(areaId))
                return new ReturnValueModel { Code = 400, Msg = "areaId AND areaName 重复" };

            Stopwatch watch = Stopwatch.StartNew();
            var fingerAll = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

            var startDate = string.IsNullOrEmpty(datetime) ? DateTime.Now : Convert.ToDateTime(datetime);
            var sql = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE Areaname={0} UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
            var areaAll = _rep.SqlQuery<Area>(sql, string.IsNullOrEmpty(areaName) ? "上海市" : areaName).Select(p => new Area { YunCode = p.YunCode }).ToList();

            List<string> arrt = new List<string>();
            foreach (var item in areaAll)
                arrt.Add(item.YunCode);
            string[] arrt2 = arrt.ToArray();

            var PlaceOfOriginPriceAll = from a in _rep.Where<PlaceOfOriginPrice>(p => p.Status == 0)
                                        where a.CreateTime >= startDate.AddMonths(-3) && a.CreateTime <= startDate
                                        join m in _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0) on a.PlaceOfOriginId equals m.Id
                                        join r in _rep.Where<Area>(p => p.Status == 0) on m.AreaUnCode equals r.YunCode
                                        where string.IsNullOrEmpty(areaName) && string.IsNullOrEmpty(areaId) ? a.Status == 0 : !string.IsNullOrEmpty(areaId) ? r.YunCode == areaId : arrt2.Contains(r.YunCode)
                                        // join y in _rep.Where<YscUser>(p => p.Status == 0) on a.UserId equals y.Id
                                        join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId equals f.FishCode
                                        join d in _rep.Where<Dictionary>(p => p.Status == 0) on f.Type equals d.Id
                                        select new
                                        {
                                            a.Id,
                                            f.FishName,
                                            fishType = d.Name,
                                            // y.UserName,
                                            a.UserId,
                                            m.Address,
                                            a.AveragePrice,
                                            a.CreateTime
                                        };


            var model = PlaceOfOriginPriceAll.OrderByDescending(p => p.CreateTime)
                    .WhereIf(p => p.FishName == fishName, string.IsNullOrEmpty(fishName) == false)
                    .WhereIf(p => p.fishType == fishType, string.IsNullOrEmpty(fishType) == false)
                    .ToPaginationList(index, size)
                    .ToList().Join(_rep.Where<YscUser>(p => p.Status == 0), a => a.UserId, y => y.Id, (a, y) => new { a.Id, a.FishName, UserName = System.Web.HttpUtility.UrlDecode(y.UserName, Encoding.UTF8), a.Address, a.AveragePrice, a.CreateTime, a.UserId }).ToList();


            watch.Stop();
            Stopwatch watch1 = Stopwatch.StartNew();

            List<string> arrtIds = new List<string>();
            foreach (var item in model)
                arrtIds.Add(item.Id);
            string[] arrtId = arrtIds.ToArray();

            var marketPricesAll = from a in _rep.Where<PlaceOfOriginPrices>(p => arrtId.Contains(p.PlaceOfOriginPriceId))
                                  join f in _rep.Where<FishSpecies>(s => s.Status == 0) on a.DescriptionId.Trim() equals f.FishCode
                                  select new MarketPricesModel
                                  {
                                      MarketPriceId = a.PlaceOfOriginPriceId,
                                      Description = f.Description.Trim(),
                                      Price = a.Price
                                  };

            var marketPricessql = marketPricesAll.ToSql();

            var marketPricesList = marketPricesAll.DistinctBy(a => new { Description = a.Description.Trim() }).ToList();



            var models = model
            .Select(p => new MarketPriceModel
            {
                Id = p.Id,
                FishName = p.FishName,
                UserId = p.UserId,
                UserName = p.UserName,
                AveragePrice = p.AveragePrice,
                UnitAddress = p.Address,
                CreateTime = p.CreateTime,
                MarketPricesModel = marketPricesList.Where(a => a.MarketPriceId == p.Id).ToList()
            });

            watch1.Stop();


            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = models, Timer = watch.ElapsedMilliseconds, Timer1 = watch1.ElapsedMilliseconds } };
        }

        /// <summary>
        /// 市场鱼价详情
        /// </summary>
        /// <param name="marketPriceId">鱼价Id</param>
        /// <param name="priceType">报价类型0:市场价 1：产地价</param>
        /// <returns></returns>
        public ReturnValueModel GetMarketPrice(string marketPriceId, int priceType)
        {
            if (string.IsNullOrEmpty(marketPriceId))
                return new ReturnValueModel { Code = 400, Msg = "鱼价主键Does Not Exist" };

            if (priceType == 0)
            {
                var marketPrice = from a in _rep.Where<MarketPrice>(p => p.Id == marketPriceId)
                                  join m in _rep.Where<MarketUnit>(p => p.Status == 0) on a.MarketId equals m.Id
                                  join y in _rep.Where<YscUser>(p => p.Status == 0) on a.UserId equals y.Id
                                  join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId equals f.FishCode
                                  join u in _rep.Where<MediaImage>(p => p.Status == 0) on f.FishName equals u.Type into u
                                  from ui in u.DefaultIfEmpty()
                                  select (new
                                  {
                                      a.Id,
                                      f.FishName,
                                      UnitName = m.MarketName,
                                      UserName = System.Web.HttpUtility.UrlDecode(y.UserName, Encoding.UTF8),
                                      UnitAddress = m.Address,
                                      m.ContactsName,
                                      m.ContactsPhone,
                                      a.AveragePrice,
                                      a.CreateTime,
                                      FishUrl = string.IsNullOrEmpty(ui.FileUrl) ? ui.FileUrl : string.Format("https://fishopeni.cnfm.com.cn:8095" + ui.FileUrl)
                                  });

                //鱼种信息
                var marketPrices = marketPrice.ToList();
                var marketPricesModel = _rep.Where<MarketPrices>(a => a.MarketPriceId == marketPrices.FirstOrDefault().Id).Join(_rep.Where<FishSpecies>(s => s.Status == 0), a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel
                {
                    Description = f.Description.Trim(),
                    Price = a.Price
                }).DistinctBy(a => new { a.Description }).ToList();

                var modelsM = marketPrices
                      .Select(p => new MarketPriceModel
                      {
                          Id = p.Id,
                          FishName = p.FishName,
                          UnitName = p.UnitName,
                          UserName = p.UserName,
                          UnitAddress = p.UnitAddress,
                          ContactsName = p.ContactsName,
                          ContactsPhone = p.ContactsPhone,
                          AveragePrice = p.AveragePrice,
                          FishUrl = p.FishUrl,
                          CreateTime = p.CreateTime,
                          MarketPricesModel = marketPricesModel
                      });

                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = modelsM.Count() > 0 ? modelsM.FirstOrDefault() : null } };
            }

            var placeOfOriginPrice = from a in _rep.Where<PlaceOfOriginPrice>(p => p.Id == marketPriceId)
                                     join m in _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0) on a.PlaceOfOriginId equals m.Id
                                     join y in _rep.Where<YscUser>(p => p.Status == 0) on a.UserId equals y.Id
                                     join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId equals f.FishCode
                                     join u in _rep.Where<MediaImage>(p => p.Status == 0) on f.FishName equals u.Type into u
                                     from ui in u.DefaultIfEmpty()
                                     select (new
                                     {
                                         a.Id,
                                         f.FishName,
                                         UnitName = m.PlaceOriginName,
                                         UserName = System.Web.HttpUtility.UrlDecode(y.UserName, Encoding.UTF8),
                                         UnitAddress = m.Address,
                                         m.ContactsName,
                                         m.ContactsPhone,
                                         a.AveragePrice,
                                         a.CreateTime,
                                         FishUrl = string.IsNullOrEmpty(ui.FileUrl) ? ui.FileUrl : string.Format("https://fishopeni.cnfm.com.cn:8095" + ui.FileUrl)
                                     });

            //鱼种信息
            var placeOfOriginPrices = placeOfOriginPrice.ToList();
            var placeOfOriginsModel = _rep.Where<PlaceOfOriginPrices>(a => a.PlaceOfOriginPriceId == placeOfOriginPrices.FirstOrDefault().Id).Join(_rep.Where<FishSpecies>(s => s.Status == 0), a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel
            {
                Description = f.Description.Trim(),
                Price = a.Price
            }).DistinctBy(a => new { a.Description }).ToList();

            var models = placeOfOriginPrices
                  .Select(p => new MarketPriceModel
                  {
                      Id = p.Id,
                      FishName = p.FishName,
                      UnitName = p.UnitName,
                      UserName = p.UserName,
                      UnitAddress = p.UnitAddress,
                      ContactsName = p.ContactsName,
                      ContactsPhone = p.ContactsPhone,
                      AveragePrice = p.AveragePrice,
                      FishUrl = p.FishUrl,
                      CreateTime = p.CreateTime,
                      MarketPricesModel = placeOfOriginsModel
                  });

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = models.Count() > 0 ? models.FirstOrDefault() : null } };

        }

        /// <summary>
        /// 塘口渔家详情
        /// </summary>
        /// <param name="marketPriceId"></param>
        /// <returns></returns>
        public ReturnValueModel GetPlaceOfOriginPrice(string marketPriceId)
        {
            if (string.IsNullOrEmpty(marketPriceId))
                return new ReturnValueModel { Code = 400, Msg = "鱼价主键Does Not Exist" };

            var marketPrice = from a in _rep.Where<PlaceOfOriginPrice>(p => p.Id == marketPriceId)
                              join m in _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0) on a.PlaceOfOriginId equals m.Id
                              join y in _rep.Where<YscUser>(p => p.Status == 0) on a.UserId equals y.Id
                              join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId equals f.FishCode
                              join u in _rep.Where<MediaImage>(p => p.Status == 0) on f.FishName equals u.Type into u
                              from ui in u.DefaultIfEmpty()
                              select (new
                              {
                                  a.Id,
                                  f.FishName,
                                  UnitName = m.PlaceOriginName,
                                  y.UserName,
                                  UnitAddress = m.Address,
                                  m.ContactsName,
                                  m.ContactsPhone,
                                  a.AveragePrice,
                                  FishUrl = string.IsNullOrEmpty(ui.FileUrl) ? ui.FileUrl : string.Format("https://fishopeni.cnfm.com.cn:8095" + ui.FileUrl)
                              });

            //鱼种信息
            var marketPrices = marketPrice.ToList();
            var marketPricesModel = _rep.Where<PlaceOfOriginPrices>(a => a.PlaceOfOriginPriceId == marketPrices.FirstOrDefault().Id).Join(_rep.Where<FishSpecies>(s => s.Status == 0), a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel
            {
                Description = f.Description.Trim(),
                Price = a.Price
            }).DistinctBy(a => new { a.Description }).ToList();

            var models = marketPrices
                  .Select(p => new MarketPriceModel
                  {
                      Id = p.Id,
                      FishName = p.FishName,
                      UnitName = p.UnitName,
                      UserName = p.UserName,
                      UnitAddress = p.UnitAddress,
                      ContactsName = p.ContactsName,
                      ContactsPhone = p.ContactsPhone,
                      AveragePrice = p.AveragePrice,
                      FishUrl = p.FishUrl,
                      MarketPricesModel = marketPricesModel
                  });

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = models.Count() > 0 ? models.FirstOrDefault() : null } };
        }

        /// <summary>
        /// 市场鱼价详情_规格对比报表
        /// </summary>
        /// <param name="marketPriceId"></param>
        /// <param name="priceType">报价类型0:市场价 1：产地价</param>
        /// <returns></returns>
        public ReturnValueModel GetMarketPriceComparedReport(string marketPriceId, int priceType)
        {
            if (string.IsNullOrEmpty(marketPriceId))
                return new ReturnValueModel { Code = 400, Msg = "鱼价主键Does Not Exist" };

            if (priceType == 0)
            {
                var marketPriceAllM = _rep.Where<MarketPrices>(p => p.MarketPriceId == marketPriceId)
               .Join(_rep.Where<FishSpecies>(p => true), m => m.DescriptionId.Trim(), f => f.FishCode, (m, f) => new { m.Price, m.CreateTime, DescriptionId = m.DescriptionId.Trim(), f.Description })
               .ToList();
                var nationalPriceAllM = _rep.Where<MarketPrices>(p => p.CreateTime == marketPriceAllM.FirstOrDefault().CreateTime).ToList();


                List<MarketPriceComparedReport> modelsM = new List<MarketPriceComparedReport>();

                foreach (var item in marketPriceAllM)
                {
                    MarketPriceComparedReport price = new MarketPriceComparedReport()
                    {
                        Description = item.Description.Trim(),
                        Price = item.Price,
                        NationalPrice = nationalPriceAllM.Where(p => p.DescriptionId.Trim() == item.DescriptionId.Trim()).Average(a => a.Price)
                    };
                    modelsM.Add(price);
                }

                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = modelsM } };
            }

            var marketPriceAll = _rep.Where<PlaceOfOriginPrices>(p => p.PlaceOfOriginPriceId == marketPriceId)
               .Join(_rep.Where<FishSpecies>(p => true), m => m.DescriptionId.Trim(), f => f.FishCode, (m, f) => new { m.Price, m.CreateTime, DescriptionId = m.DescriptionId.Trim(), f.Description })
               .ToList();
            var nationalPriceAll = _rep.Where<PlaceOfOriginPrices>(p => p.CreateTime == marketPriceAll.FirstOrDefault().CreateTime).ToList();


            List<MarketPriceComparedReport> models = new List<MarketPriceComparedReport>();

            foreach (var item in marketPriceAll)
            {
                MarketPriceComparedReport price = new MarketPriceComparedReport()
                {
                    Description = item.Description.Trim(),
                    Price = item.Price,
                    NationalPrice = nationalPriceAll.Where(p => p.DescriptionId.Trim() == item.DescriptionId.Trim()).Average(a => a.Price)
                };
                models.Add(price);
            }

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = models } };
        }

        /// <summary>
        /// 塘口鱼价详情_规格对比报表
        /// </summary>
        /// <param name="marketPriceId"></param>
        /// <returns></returns>
        public ReturnValueModel GetPlaceOfOriginPriceComparedReport(string marketPriceId)
        {
            if (string.IsNullOrEmpty(marketPriceId))
                return new ReturnValueModel { Code = 400, Msg = "鱼价主键Does Not Exist" };

            var marketPriceAll = _rep.Where<PlaceOfOriginPrices>(p => p.PlaceOfOriginPriceId == marketPriceId)
                .Join(_rep.Where<FishSpecies>(p => true), m => m.DescriptionId.Trim(), f => f.FishCode, (m, f) => new { m.Price, m.CreateTime, DescriptionId = m.DescriptionId.Trim(), f.Description })
                .ToList();
            var nationalPriceAll = _rep.Where<PlaceOfOriginPrices>(p => p.CreateTime == marketPriceAll.FirstOrDefault().CreateTime).ToList();


            List<MarketPriceComparedReport> models = new List<MarketPriceComparedReport>();

            foreach (var item in marketPriceAll)
            {
                MarketPriceComparedReport price = new MarketPriceComparedReport()
                {
                    Description = item.Description.Trim(),
                    Price = item.Price,
                    NationalPrice = nationalPriceAll.Where(p => p.DescriptionId.Trim() == item.DescriptionId.Trim()).Average(a => a.Price)
                };
                models.Add(price);
            }

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = models } };
        }

        /// <summary>
        /// 市场鱼价详情_规格走势报表
        /// </summary>
        /// <param name="marketPriceId">鱼价Id</param>
        /// <param name="type">报表类型:0一周，1三月2一年</param>
        /// <param name="priceType">报价类型0:市场价 1：产地价</param>
        /// <returns></returns>
        public ReturnValueModel GetMarketPriceTrendReport(string marketPriceId, int type, int priceType)
        {
            if (string.IsNullOrEmpty(marketPriceId))
                return new ReturnValueModel { Code = 400, Msg = "鱼价主键Does Not Exist" };

            if (priceType == 0)
            {
                var dateTimeM = DateTime.Now;
                string AreUnCodeM = string.Empty;
                var fishIdM = _rep.FirstOrDefault<MarketPrice>(p => p.Id == marketPriceId).FishId;
                dateTimeM = _rep.FirstOrDefault<MarketPrice>(p => p.Id == marketPriceId).CreateTime;
                var areaCodeM = _rep.Where<MarketPrice>(p => p.Id == marketPriceId)
                    .Join(_rep.Where<MarketUnit>(p => true), a => a.MarketId, u => u.Id, (a, u) => new { u.AreaUnCode }).FirstOrDefault().AreaUnCode;
                var aterItmeM = _rep.FirstOrDefault<Area>(p => p.YunCode == areaCodeM);
                if (aterItmeM.Level == 3)
                    AreUnCodeM = aterItmeM.PunCode;
                else
                    AreUnCodeM = aterItmeM.YunCode;


                var sqlM = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
                var areaAllM = _rep.SqlQuery<Area>(sqlM, AreUnCodeM).ToList();
                List<string> arrtM = new List<string>();
                foreach (var item in areaAllM)
                    arrtM.Add(item.YunCode);
                string[] arrt2M = arrtM.ToArray();


                if (type == 0)
                {
                    var MarketPriceTrendReport = _rep.Where<MarketPrice>(p => p.FishId == fishIdM && p.CreateTime >= Convert.ToDateTime(dateTimeM.AddDays(-7))).ToList()
                        .GroupBy(p => new
                        {
                            Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                        })
                        .Select(p => new
                        {
                            p.Key.Day,
                            Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                        }).ToList();

                    var MarketPriceTrendAreaReportAll = from a in _rep.Where<MarketPrice>(p => p.FishId == fishIdM && p.CreateTime >= Convert.ToDateTime(dateTimeM.AddDays(-7)))
                                                        join m in _rep.Where<MarketUnit>(p => true) on a.MarketId equals m.Id
                                                        join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                        where arrt2M.Contains(r.YunCode)
                                                        select new
                                                        {
                                                            a.CreateTime,
                                                            a.AveragePrice
                                                        };
                    var MarketPriceTrendAreaReport = MarketPriceTrendAreaReportAll.ToList()
                                                       .GroupBy(p => new
                                                       {
                                                           Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                                                       })
                                                      .Select(p => new
                                                      {
                                                          p.Key.Day,
                                                          Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                                                      }).ToList();


                    return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendReport, Area = MarketPriceTrendReport } } };
                }

                if (type == 1)
                {
                    var MarketPriceTrendReport = _rep.Where<MarketPrice>(p => p.FishId == fishIdM && p.CreateTime >= dateTimeM.AddMonths(-3)).ToList()
                      .GroupBy(p => new
                      {
                          Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                      })
                      .Select(p => new
                      {
                          p.Key.Month,
                          Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                      }).ToList();

                    var MarketPriceTrendAreaReportAll = from a in _rep.Where<MarketPrice>(p => p.FishId == fishIdM && p.CreateTime >= Convert.ToDateTime(dateTimeM.AddDays(-7)))
                                                        join m in _rep.Where<MarketUnit>(p => true) on a.MarketId equals m.Id
                                                        join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                        where arrt2M.Contains(r.YunCode)
                                                        select new
                                                        {
                                                            a.CreateTime,
                                                            a.AveragePrice
                                                        };
                    var MarketPriceTrendAreaReport = MarketPriceTrendAreaReportAll.ToList()
                                                       .GroupBy(p => new
                                                       {
                                                           Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                                                       })
                                                      .Select(p => new
                                                      {
                                                          p.Key.Month,
                                                          Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                                                      }).ToList();


                    return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendReport, Area = MarketPriceTrendReport } } };
                }

                var MarketPriceTrendYReportM = _rep.Where<MarketPrice>(p => p.FishId == fishIdM && p.CreateTime >= dateTimeM.AddMonths(-12)).ToList()
                      .GroupBy(p => new
                      {
                          Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                      })
                      .Select(p => new
                      {
                          p.Key.Month,
                          Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                      }).ToList();

                var MarketPriceTrendAreaYReportAllM = from a in _rep.Where<MarketPrice>(p => p.FishId == fishIdM && p.CreateTime >= Convert.ToDateTime(dateTimeM.AddDays(-7)))
                                                      join m in _rep.Where<MarketUnit>(p => true) on a.MarketId equals m.Id
                                                      join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                      where arrt2M.Contains(r.YunCode)
                                                      select new
                                                      {
                                                          a.CreateTime,
                                                          a.AveragePrice
                                                      };
                var MarketPriceTrendAreaYReportM = MarketPriceTrendAreaYReportAllM.ToList()
                                                   .GroupBy(p => new
                                                   {
                                                       Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                                                   })
                                                  .Select(p => new
                                                  {
                                                      p.Key.Month,
                                                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2),
                                                      Static = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2) > 10 ? "是" : "否"
                                                  }).OrderByDescending(p => p.Month).ToList();


                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendAreaYReportM, Area = MarketPriceTrendAreaYReportM } } };

            }
            var dateTime = DateTime.Now;
            string AreUnCode = string.Empty;
            var fishId = _rep.FirstOrDefault<PlaceOfOriginPrice>(p => p.Id == marketPriceId).FishId;
            dateTime = _rep.FirstOrDefault<PlaceOfOriginPrice>(p => p.Id == marketPriceId).CreateTime;
            var areaCode = _rep.Where<PlaceOfOriginPrice>(p => p.Id == marketPriceId)
                .Join(_rep.Where<PlaceOfOriginUnit>(p => true), a => a.PlaceOfOriginId, u => u.Id, (a, u) => new { u.AreaUnCode }).FirstOrDefault().AreaUnCode;
            var aterItme = _rep.FirstOrDefault<Area>(p => p.YunCode == areaCode);
            if (aterItme.Level == 3)
                AreUnCode = aterItme.PunCode;
            else
                AreUnCode = aterItme.YunCode;


            var sql = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
            var areaAll = _rep.SqlQuery<Area>(sql, AreUnCode).ToList();
            List<string> arrt = new List<string>();
            foreach (var item in areaAll)
                arrt.Add(item.YunCode);
            string[] arrt2 = arrt.ToArray();


            if (type == 0)
            {
                var MarketPriceTrendReport = _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= Convert.ToDateTime(dateTime.AddDays(-7))).ToList()
                    .GroupBy(p => new
                    {
                        Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                    })
                    .Select(p => new
                    {
                        p.Key.Day,
                        Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                    }).ToList();

                var MarketPriceTrendAreaReportAll = from a in _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= Convert.ToDateTime(dateTime.AddDays(-7)))
                                                    join m in _rep.Where<PlaceOfOriginUnit>(p => true) on a.PlaceOfOriginId equals m.Id
                                                    join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                    where arrt2.Contains(r.YunCode)
                                                    select new
                                                    {
                                                        a.CreateTime,
                                                        a.AveragePrice
                                                    };
                var MarketPriceTrendAreaReport = MarketPriceTrendAreaReportAll.ToList()
                                                   .GroupBy(p => new
                                                   {
                                                       Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                                                   })
                                                  .Select(p => new
                                                  {
                                                      p.Key.Day,
                                                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                                                  }).ToList();


                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendReport, Area = MarketPriceTrendReport } } };
            }

            if (type == 1)
            {
                var MarketPriceTrendReport = _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= dateTime.AddMonths(-3)).ToList()
                  .GroupBy(p => new
                  {
                      Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                  })
                  .Select(p => new
                  {
                      p.Key.Month,
                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                  }).ToList();

                var MarketPriceTrendAreaReportAll = from a in _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= Convert.ToDateTime(dateTime.AddDays(-7)))
                                                    join m in _rep.Where<PlaceOfOriginUnit>(p => true) on a.PlaceOfOriginId equals m.Id
                                                    join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                    where arrt2.Contains(r.YunCode)
                                                    select new
                                                    {
                                                        a.CreateTime,
                                                        a.AveragePrice
                                                    };
                var MarketPriceTrendAreaReport = MarketPriceTrendAreaReportAll.ToList()
                                                   .GroupBy(p => new
                                                   {
                                                       Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                                                   })
                                                  .Select(p => new
                                                  {
                                                      p.Key.Month,
                                                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                                                  }).ToList();


                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendReport, Area = MarketPriceTrendReport } } };
            }

            var MarketPriceTrendYReport = _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= dateTime.AddMonths(-12)).ToList()
                  .GroupBy(p => new
                  {
                      Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                  })
                  .Select(p => new
                  {
                      p.Key.Month,
                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                  }).ToList();

            var MarketPriceTrendAreaYReportAll = from a in _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= Convert.ToDateTime(dateTime.AddDays(-7)))
                                                 join m in _rep.Where<PlaceOfOriginUnit>(p => true) on a.PlaceOfOriginId equals m.Id
                                                 join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                 where arrt2.Contains(r.YunCode)
                                                 select new
                                                 {
                                                     a.CreateTime,
                                                     a.AveragePrice
                                                 };
            var MarketPriceTrendAreaYReport = MarketPriceTrendAreaYReportAll.ToList()
                                               .GroupBy(p => new
                                               {
                                                   Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                                               })
                                              .Select(p => new
                                              {
                                                  p.Key.Month,
                                                  Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2),
                                                  Static = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2) > 10 ? "是" : "否"
                                              }).OrderByDescending(p=>p.Month).ToList();

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendYReport, Area = MarketPriceTrendYReport } } };

        }

        /// <summary>
        /// 塘口鱼价详情_规格走势报表
        /// </summary>
        /// <param name="marketPriceId">鱼价Id</param>
        /// <param name="type">报表类型:0一周，1三月2一年</param>
        /// <returns></returns>
        public ReturnValueModel GetPlaceOfOriginPriceTrendReport(string marketPriceId, int type)
        {
            if (string.IsNullOrEmpty(marketPriceId))
                return new ReturnValueModel { Code = 400, Msg = "鱼价主键Does Not Exist" };

            var dateTime = DateTime.Now;
            string AreUnCode = string.Empty;
            var fishId = _rep.FirstOrDefault<PlaceOfOriginPrice>(p => p.Id == marketPriceId).FishId;
            dateTime = _rep.FirstOrDefault<PlaceOfOriginPrice>(p => p.Id == marketPriceId).CreateTime;
            var areaCode = _rep.Where<PlaceOfOriginPrice>(p => p.Id == marketPriceId)
                .Join(_rep.Where<PlaceOfOriginUnit>(p => true), a => a.PlaceOfOriginId, u => u.Id, (a, u) => new { u.AreaUnCode }).FirstOrDefault().AreaUnCode;
            var aterItme = _rep.FirstOrDefault<Area>(p => p.YunCode == areaCode);
            if (aterItme.Level == 3)
                AreUnCode = aterItme.PunCode;
            else
                AreUnCode = aterItme.YunCode;


            var sql = "WITH CTE AS ( SELECT YUnCode,PUnCode FROM dbo.Area WHERE YUnCode={0} UNION ALL SELECT a.YUnCode,a.PUnCode FROM dbo.Area a INNER JOIN CTE b ON b.YUnCode=a.PUnCode) SELECT a.*  FROM dbo.Area a INNER JOIN CTE t ON a.YUnCode=t.YUnCode";
            var areaAll = _rep.SqlQuery<Area>(sql, AreUnCode).ToList();
            List<string> arrt = new List<string>();
            foreach (var item in areaAll)
                arrt.Add(item.YunCode);
            string[] arrt2 = arrt.ToArray();


            if (type == 0)
            {
                var MarketPriceTrendReport = _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= Convert.ToDateTime(dateTime.AddDays(-7))).ToList()
                    .GroupBy(p => new
                    {
                        Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                    })
                    .Select(p => new
                    {
                        p.Key.Day,
                        Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                    }).ToList();

                var MarketPriceTrendAreaReportAll = from a in _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= Convert.ToDateTime(dateTime.AddDays(-7)))
                                                    join m in _rep.Where<PlaceOfOriginUnit>(p => true) on a.PlaceOfOriginId equals m.Id
                                                    join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                    where arrt2.Contains(r.YunCode)
                                                    select new
                                                    {
                                                        a.CreateTime,
                                                        a.AveragePrice
                                                    };
                var MarketPriceTrendAreaReport = MarketPriceTrendAreaReportAll.ToList()
                                                   .GroupBy(p => new
                                                   {
                                                       Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                                                   })
                                                  .Select(p => new
                                                  {
                                                      p.Key.Day,
                                                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                                                  }).ToList();


                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendReport, Area = MarketPriceTrendReport } } };
            }

            if (type == 1)
            {
                var MarketPriceTrendReport = _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= dateTime.AddMonths(-3)).ToList()
                  .GroupBy(p => new
                  {
                      Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                  })
                  .Select(p => new
                  {
                      p.Key.Month,
                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                  }).ToList();

                var MarketPriceTrendAreaReportAll = from a in _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= Convert.ToDateTime(dateTime.AddDays(-7)))
                                                    join m in _rep.Where<PlaceOfOriginUnit>(p => true) on a.PlaceOfOriginId equals m.Id
                                                    join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                    where arrt2.Contains(r.YunCode)
                                                    select new
                                                    {
                                                        a.CreateTime,
                                                        a.AveragePrice
                                                    };
                var MarketPriceTrendAreaReport = MarketPriceTrendAreaReportAll.ToList()
                                                   .GroupBy(p => new
                                                   {
                                                       Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                                                   })
                                                  .Select(p => new
                                                  {
                                                      p.Key.Month,
                                                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                                                  }).ToList();


                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendReport, Area = MarketPriceTrendReport } } };
            }

            var MarketPriceTrendYReport = _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= dateTime.AddMonths(-12)).ToList()
                  .GroupBy(p => new
                  {
                      Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                  })
                  .Select(p => new
                  {
                      p.Key.Month,
                      Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                  }).ToList();

            var MarketPriceTrendAreaYReportAll = from a in _rep.Where<PlaceOfOriginPrice>(p => p.FishId == fishId && p.CreateTime >= Convert.ToDateTime(dateTime.AddDays(-7)))
                                                 join m in _rep.Where<PlaceOfOriginUnit>(p => true) on a.PlaceOfOriginId equals m.Id
                                                 join r in _rep.Where<Area>(p => true) on m.AreaUnCode equals r.YunCode
                                                 where arrt2.Contains(r.YunCode)
                                                 select new
                                                 {
                                                     a.CreateTime,
                                                     a.AveragePrice
                                                 };
            var MarketPriceTrendAreaYReport = MarketPriceTrendAreaYReportAll.ToList()
                                               .GroupBy(p => new
                                               {
                                                   Month = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Month")
                                               })
                                              .Select(p => new
                                              {
                                                  p.Key.Month,
                                                  Price = Math.Round(Convert.ToDecimal(p.Average(a => a.AveragePrice)), 2)
                                              }).ToList();

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = new { National = MarketPriceTrendYReport, Area = MarketPriceTrendYReport } } };
        }

        /// <summary>
        /// 市场鱼价详情_消费指导
        /// </summary>
        /// <param name="marketPriceId"></param>
        /// <param name="priceType">报价类型0:市场价 1：产地价</param>
        /// <returns></returns>
        public ReturnValueModel GetMarketPriceXFZD(string marketPriceId, int priceType)
        {
            if (string.IsNullOrEmpty(marketPriceId))
                return new ReturnValueModel { Code = 400, Msg = "鱼价主键Does Not Exist" };

            if (priceType == 0)
            {
                var fishTypeM = _rep.Where<MarketPrice>(p => p.Id == marketPriceId)
               .Join(_rep.Where<FishSpecies>(p => true), a => a.FishId.Trim(), f => f.FishCode, (a, f) => new { f.YingYang, f.PengRen, f.XuanGou, f.BaoXian, f.TiShi })
               .ToList();

                var itemM = fishTypeM.FirstOrDefault();

                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = itemM } };
            }

            var fishType = _rep.Where<PlaceOfOriginPrice>(p => p.Id == marketPriceId)
                .Join(_rep.Where<FishSpecies>(p => true), a => a.FishId.Trim(), f => f.FishCode, (a, f) => new { f.YingYang, f.PengRen, f.XuanGou, f.BaoXian, f.TiShi })
                .ToList();

            var item = fishType.FirstOrDefault();

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = item } };
        }

        /// <summary>
        /// 市场鱼价详情_介绍
        /// </summary>
        /// <param name="marketPriceId"></param>
        /// <param name="priceType">报价类型0:市场价 1：产地价</param>
        /// <returns></returns>
        public ReturnValueModel GetMarketPriceIntroduction(string marketPriceId, int priceType)
        {
            if (string.IsNullOrEmpty(marketPriceId))
                return new ReturnValueModel { Code = 400, Msg = "鱼价主键Does Not Exist" };

            if (priceType == 0)
            {
                var fishTypeM = _rep.Where<MarketPrice>(p => p.Id == marketPriceId)
                            .Join(_rep.Where<FishSpecies>(p => true), a => a.FishId.Trim(), f => f.FishCode, (a, f) => new { f.SuName, f.EnglishName, f.LatinName, f.Introduction })
                            .ToList();

                var itemM = fishTypeM.FirstOrDefault();

                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = itemM } };
            }

            var fishType = _rep.Where<PlaceOfOriginPrice>(p => p.Id == marketPriceId)
             .Join(_rep.Where<FishSpecies>(p => true), a => a.FishId.Trim(), f => f.FishCode, (a, f) => new { f.SuName, f.EnglishName, f.LatinName, f.Introduction })
             .ToList();

            var item = fishType.FirstOrDefault();

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Date = item } };
        }

        /// <summary>
        /// 用户历史报价
        /// </summary>
        /// <param name="index">页码</param>
        /// <param name="size">数量</param>
        /// <param name="userId"></param>
        /// <param name="MarketId">市场Id</param>
        /// <param name="dateTime">添加时间</param>
        /// <returns></returns>
        public ReturnValueModel GetMarketPriceHistoryAll(int index, int size, string userId, string MarketId, string dateTime)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 400, Msg = "用户主键Does Not Exist" };
            if (string.IsNullOrEmpty(MarketId) && !string.IsNullOrEmpty(dateTime) || !string.IsNullOrEmpty(MarketId) && string.IsNullOrEmpty(dateTime))
                return new ReturnValueModel { Code = 400, Msg = "市场Id与时间错误!" };


            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 401, Msg = "用户凭证过期!" };

            var userItem = _rep.FirstOrDefault<YscUser>(p => p.Id == userId);
            if (userItem.IsAttest == false)
                return new ReturnValueModel { Code = 401, Msg = "用户没有权限!" };


            if (!_rep.FirstOrDefault<Dictionary>(p => p.Id == userItem.AttestType).Name.Contains("产地"))
            {
                var fishAllM = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

                var marketPriceHistoryListM = from a in _rep.Where<MarketPrice>(p => p.Status == 0 && p.UserId == userId)
                                              join m in _rep.Where<MarketUnit>(p => p.Status == 0) on a.MarketId equals m.Id
                                              join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId.Trim() equals f.FishCode
                                              select new
                                              {
                                                  a.MarketPrices,
                                                  a.Id,
                                                  a.FishId,
                                                  f.FishName,
                                                  a.UserId,
                                                  a.AveragePrice,
                                                  MarketId = m.Id,
                                                  UnitAddress = m.Address,
                                                  m.MarketName,
                                                  a.CreateTime
                                              };

                var listM = marketPriceHistoryListM
                    .WhereIf(p => p.MarketId == MarketId, string.IsNullOrEmpty(MarketId) == false)
                  .WhereIf(p => UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(dateTime), "Day"), string.IsNullOrEmpty(dateTime) == false);
                //  .ToList();

                //var listsql = marketPriceHistoryList
                //    .WhereIf(p => p.MarketId == MarketId, string.IsNullOrEmpty(MarketId) == false)
                //    .WhereIf(p => p.CreateTime == Convert.ToDateTime(dateTime), string.IsNullOrEmpty(dateTime) == false).ToSql();

                var marketPriceHistoryAllM = listM.OrderByDescending(p => p.CreateTime)
                    .ToPaginationList(index, size)
                    .ToList()
                     .Select(p => new MarketPriceModel
                     {
                         Id = p.Id,
                         FishId = p.FishId,
                         FishName = p.FishName,
                         UserId = p.UserId,
                         MarketId = p.MarketId,
                         MarketName = p.MarketName,
                         UnitAddress = p.UnitAddress,
                         AveragePrice = p.AveragePrice,
                         CreateTime = p.CreateTime,
                         MarketPricesModel = p.MarketPrices.Join(fishAllM, a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price, FishName = f.FishName }).ToList()
                         //.Join(fishAll.Where(a => a.Status == 0), a => a.FishName, f => f.FishName, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price }).ToList(),
                     }).ToList();


                foreach (var item in marketPriceHistoryAllM)
                {
                    var Descriptionlist = fishAllM.Where(p => p.FishName == item.FishName).ToList().Select(p => new MarketPricesModel
                    {
                        DescriptionId = p.FishCode,
                        Description = p.Description.Trim(),
                        Price = 0
                    }).ToList();
                    foreach (var pricesItem in Descriptionlist)
                    {
                        if (item.MarketPricesModel.Where(p => p.Description == pricesItem.Description).Count() == 0)
                            item.MarketPricesModel.Add(pricesItem);
                    }

                    //var Descriptionlist = fishAll.Where(p => p.FishName == item.FishName).ToList().Select(p => new { p.Description, DescriptionId = p.FishCode }).Except(item.MarketPricesModel.Select(p => new { p.Description, p.DescriptionId })).ToList().Select(p => new MarketPricesModel
                    //{
                    //    DescriptionId = p.DescriptionId.Trim(),
                    //    Description = p.Description.Trim(),
                    //    Price = 0
                    //}).DistinctBy(p=>p.Description).ToList();               
                }


                var modelsM = marketPriceHistoryAllM
                     .GroupBy(p => new
                     {
                         p.MarketName,
                         Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                     })
                     .Select(p => new
                     {
                         p.Key.Day,
                         p.Key.MarketName,
                         HistoryDate = p
                     });

                return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = modelsM } };
            }

            var fishAll = _rep.Where<FishSpecies>(p => p.Status == 0).ToList();

            var marketPriceHistoryList = from a in _rep.Where<PlaceOfOriginPrice>(p => p.Status == 0 && p.UserId == userId)
                                         join m in _rep.Where<PlaceOfOriginUnit>(p => p.Status == 0) on a.PlaceOfOriginId equals m.Id
                                         join f in _rep.Where<FishSpecies>(p => p.Status == 0) on a.FishId.Trim() equals f.FishCode
                                         select new
                                         {
                                             a.PlaceOfOriginPricesModel,
                                             a.Id,
                                             a.FishId,
                                             f.FishName,
                                             a.UserId,
                                             a.AveragePrice,
                                             MarketId = m.Id,
                                             UnitAddress = m.Address,
                                             m.PlaceOriginName,
                                             a.CreateTime
                                         };

            var list = marketPriceHistoryList
                .WhereIf(p => p.MarketId == MarketId, string.IsNullOrEmpty(MarketId) == false)
              .WhereIf(p => UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(dateTime), "Day"), string.IsNullOrEmpty(dateTime) == false);
            //  .ToList();

            //var listsql = marketPriceHistoryList
            //    .WhereIf(p => p.MarketId == MarketId, string.IsNullOrEmpty(MarketId) == false)
            //    .WhereIf(p => p.CreateTime == Convert.ToDateTime(dateTime), string.IsNullOrEmpty(dateTime) == false).ToSql();

            var marketPriceHistoryAll = list.OrderByDescending(p => p.CreateTime)
                .ToPaginationList(index, size)
                .ToList()
                 .Select(p => new MarketPriceModel
                 {
                     Id = p.Id,
                     FishId = p.FishId,
                     FishName = p.FishName,
                     UserId = p.UserId,
                     MarketId = p.MarketId,
                     MarketName = p.PlaceOriginName,
                     UnitAddress = p.UnitAddress,
                     AveragePrice = p.AveragePrice,
                     CreateTime = p.CreateTime,
                     MarketPricesModel = p.PlaceOfOriginPricesModel.Join(fishAll, a => a.DescriptionId.Trim(), f => f.FishCode, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price, FishName = f.FishName }).ToList()
                     //.Join(fishAll.Where(a => a.Status == 0), a => a.FishName, f => f.FishName, (a, f) => new MarketPricesModel { DescriptionId = a.DescriptionId.Trim(), Description = f.Description.Trim(), Price = a.Price }).ToList(),
                 }).ToList();


            foreach (var item in marketPriceHistoryAll)
            {
                var Descriptionlist = fishAll.Where(p => p.FishName == item.FishName).ToList().Select(p => new MarketPricesModel
                {
                    DescriptionId = p.FishCode,
                    Description = p.Description.Trim(),
                    Price = 0
                }).ToList();
                foreach (var pricesItem in Descriptionlist)
                {
                    if (item.MarketPricesModel.Where(p => p.Description == pricesItem.Description).Count() == 0)
                        item.MarketPricesModel.Add(pricesItem);
                }

                //var Descriptionlist = fishAll.Where(p => p.FishName == item.FishName).ToList().Select(p => new { p.Description, DescriptionId = p.FishCode }).Except(item.MarketPricesModel.Select(p => new { p.Description, p.DescriptionId })).ToList().Select(p => new MarketPricesModel
                //{
                //    DescriptionId = p.DescriptionId.Trim(),
                //    Description = p.Description.Trim(),
                //    Price = 0
                //}).DistinctBy(p=>p.Description).ToList();               
            }


            var models = marketPriceHistoryAll
                 .GroupBy(p => new
                 {
                     p.MarketName,
                     Day = UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day")
                 })
                 .Select(p => new
                 {
                     p.Key.Day,
                     p.Key.MarketName,
                     HistoryDate = p
                 });

            return new ReturnValueModel { Code = 200, Msg = "success", Result = new { Data = models } };
        }

        /// <summary>
        /// 市场鱼价新增
        /// </summary>
        /// <param name="modelAll"></param>
        /// <returns></returns>
        public ReturnValueModel AddMarketPrice(List<MarketPriceModel> modelAll, string userId)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 401, Msg = "用户凭证过期!" };

            if (modelAll.Count() == 0)
                return new ReturnValueModel { Code = 400, Msg = "提交信息不能为空!" };

            var userItem = _rep.FirstOrDefault<YscUser>(p => p.Id == userId);
            if (userItem.IsAttest == false)
                return new ReturnValueModel { Code = 401, Msg = "用户没有权限!" };


            if (!_rep.FirstOrDefault<Dictionary>(p => p.Id == userItem.AttestType).Name.Contains("产地"))
            {
                foreach (var model in modelAll)
                {
                    if (model.MarketPricesModel.Where(p => p.Price > 0).Count() == 0)
                        return new ReturnValueModel { Code = 401, Msg = "鱼价信息错误!" };
                    if (string.IsNullOrEmpty(model.MarketId))
                        return new ReturnValueModel { Code = 401, Msg = "市场信息不能为空!" };
                    if (string.IsNullOrEmpty(model.FishId))
                        return new ReturnValueModel { Code = 401, Msg = "鱼种信息不能为空!" };
                }


                List<MarketPrice> marketPriceAllM = new List<MarketPrice>();

                foreach (var model in modelAll)
                {
                    MarketPrice marketPrice = new MarketPrice()
                    {
                        Id = Guid.NewGuid().ToString(),
                        FishId = model.FishId,
                        MarketId = model.MarketId,
                        AveragePrice = model.MarketPricesModel.Where(a => a.Price > 0).Average(p => p.Price),
                        Remarks = "App直报",
                        Status = 0,
                        CreateTime = DateTime.Now,
                        CreateId = userId,
                        UserId = userId,
                        MarketPrices = model.MarketPricesModel.Where(p => p.Price > 0).Select(p => new MarketPrices()
                        {
                            Id = Guid.NewGuid().ToString(),
                            Price = p.Price,
                            DescriptionId = p.DescriptionId,
                            Remarks = "App直报",
                            CreateTime = DateTime.Now,
                            Status = 0,
                            CreateId = userId
                        }).ToList()
                    };
                    marketPrice.MarketPrices.ForEach(p => p.MarketPriceId = marketPrice.Id);
                    marketPriceAllM.Add(marketPrice);
                }


                List<string> arrtM = new List<string>();
                foreach (var item in marketPriceAllM)
                    arrtM.Add(item.MarketId);
                string[] arrt2M = arrtM.ToArray();

                var marketPriceListsqlM = _rep.Where<MarketPrice>(p => p.UserId == userId && UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(DateTime.Now), "Day") && arrt2M.Contains(p.MarketId)).ToSql();

                var marketPriceListM = _rep.Where<MarketPrice>(p => p.UserId == userId && UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(DateTime.Now), "Day") && arrt2M.Contains(p.MarketId)).ToList();
                if (marketPriceListM.Count() > 0)
                {
                    foreach (var delectPrices in marketPriceListM)
                        _rep.RemoveRange(_rep.Where<MarketPrices>(p => p.MarketPriceId == delectPrices.Id).ToList());
                    _rep.RemoveRange(marketPriceListM);
                }



                //foreach (var priceItem in marketPriceAll)
                //{
                //    _rep.Insert(priceItem);
                //}

                _rep.InsertList(marketPriceAllM);

                return new ReturnValueModel { Code = 200, Msg = "success", Result = "添加成功！" };
            }

            foreach (var model in modelAll)
            {
                if (model.MarketPricesModel.Where(p => p.Price > 0).Count() == 0)
                    return new ReturnValueModel { Code = 401, Msg = "鱼价信息错误!" };
                if (string.IsNullOrEmpty(model.MarketId))
                    return new ReturnValueModel { Code = 401, Msg = "塘口信息不能为空!" };
                if (string.IsNullOrEmpty(model.FishId))
                    return new ReturnValueModel { Code = 401, Msg = "鱼种信息不能为空!" };
            }


            List<PlaceOfOriginPrice> marketPriceAll = new List<PlaceOfOriginPrice>();

            foreach (var model in modelAll)
            {
                PlaceOfOriginPrice marketPrice = new PlaceOfOriginPrice()
                {
                    Id = Guid.NewGuid().ToString(),
                    FishId = model.FishId,
                    PlaceOfOriginId = model.MarketId,
                    AveragePrice = model.MarketPricesModel.Where(a => a.Price > 0).Average(p => p.Price),
                    Remarks = "App直报",
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = userId,
                    UserId = userId,
                    PlaceOfOriginPricesModel = model.MarketPricesModel.Where(p => p.Price > 0).Select(p => new PlaceOfOriginPrices()
                    {
                        Id = Guid.NewGuid().ToString(),
                        Price = p.Price,
                        DescriptionId = p.DescriptionId,
                        Remarks = "App直报",
                        CreateTime = DateTime.Now,
                        Status = 0,
                        CreateId = userId
                    }).ToList()
                };
                marketPrice.PlaceOfOriginPricesModel.ForEach(p => p.PlaceOfOriginPriceId = marketPrice.Id);
                marketPriceAll.Add(marketPrice);
            }


            List<string> arrt = new List<string>();
            foreach (var item in marketPriceAll)
                arrt.Add(item.PlaceOfOriginId);
            string[] arrt2 = arrt.ToArray();

            var marketPriceListsql = _rep.Where<PlaceOfOriginPrice>(p => p.UserId == userId && UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(DateTime.Now), "Day") && arrt2.Contains(p.PlaceOfOriginId)).ToSql();

            var marketPriceList = _rep.Where<PlaceOfOriginPrice>(p => p.UserId == userId && UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(DateTime.Now), "Day") && arrt2.Contains(p.PlaceOfOriginId)).ToList();
            if (marketPriceList.Count() > 0)
            {
                foreach (var delectPrices in marketPriceList)
                    _rep.RemoveRange(_rep.Where<PlaceOfOriginPrices>(p => p.PlaceOfOriginPriceId == delectPrices.Id).ToList());
                _rep.RemoveRange(marketPriceList);
            }



            //foreach (var priceItem in marketPriceAll)
            //{
            //    _rep.Insert(priceItem);
            //}

            _rep.InsertList(marketPriceAll);

            return new ReturnValueModel { Code = 200, Msg = "success", Result = "添加成功！" };
        }

        /// <summary>
        /// 市场鱼价新增(非认证)
        /// </summary>
        /// <param name="modelAll"></param>
        /// <param name="userId"></param>
        /// <returns>PricType:0 市场 1： 产地</returns>
        public ReturnValueModel AddMarketPriceNOAttest(List<MarketPriceModel> modelAll, string userId)
        {
            if (string.IsNullOrEmpty(userId))
                return new ReturnValueModel { Code = 401, Msg = "用户凭证过期!" };

            if (modelAll.Count() == 0)
                return new ReturnValueModel { Code = 400, Msg = "提交信息不能为空!" };

            if (modelAll.FirstOrDefault().PricType == 0)
            {
                foreach (var model in modelAll)
                {
                    if (model.MarketPricesModel.Where(p => p.Price > 0).Count() == 0)
                        return new ReturnValueModel { Code = 401, Msg = "鱼价信息错误!" };
                    if (string.IsNullOrEmpty(model.MarketId))
                        model.MarketId = "F4CC4659-2976-4371-BCF9-F595465568C9";
                    if (string.IsNullOrEmpty(model.FishId))
                        return new ReturnValueModel { Code = 401, Msg = "鱼种信息不能为空!" };
                }


                List<MarketPrice> marketPriceAllM = new List<MarketPrice>();

                foreach (var model in modelAll)
                {
                    MarketPrice marketPrice = new MarketPrice()
                    {
                        Id = Guid.NewGuid().ToString(),
                        FishId = model.FishId,
                        MarketId = model.MarketId,
                        AveragePrice = model.MarketPricesModel.Where(a => a.Price > 0).Average(p => p.Price),
                        Remarks = "非认证用户",
                        Status = 0,
                        CreateTime = DateTime.Now,
                        CreateId = userId,
                        UserId = userId,
                        MarketPrices = model.MarketPricesModel.Where(p => p.Price > 0).Select(p => new MarketPrices()
                        {
                            Id = Guid.NewGuid().ToString(),
                            Price = p.Price,
                            DescriptionId = p.DescriptionId,
                            CreateTime = DateTime.Now,
                            Status = 0,
                            CreateId = userId,
                            Remarks = "非认证用户"
                        }).ToList()
                    };
                    marketPrice.MarketPrices.ForEach(p => p.MarketPriceId = marketPrice.Id);
                    marketPriceAllM.Add(marketPrice);
                }


                List<string> arrtM = new List<string>();
                foreach (var item in marketPriceAllM)
                    arrtM.Add(item.MarketId);
                string[] arrt2M = arrtM.ToArray();

                var marketPriceListsqlM = _rep.Where<MarketPrice>(p => p.UserId == userId && UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(DateTime.Now), "Day") && arrt2M.Contains(p.MarketId)).ToSql();

                var marketPriceListM = _rep.Where<MarketPrice>(p => p.UserId == userId && UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(DateTime.Now), "Day") && arrt2M.Contains(p.MarketId)).ToList();
                if (marketPriceListM.Count() > 0)
                {
                    foreach (var delectPrices in marketPriceListM)
                        _rep.RemoveRange(_rep.Where<MarketPrices>(p => p.MarketPriceId == delectPrices.Id).ToList());
                    _rep.RemoveRange(marketPriceListM);
                }

                _rep.InsertList(marketPriceAllM);

                return new ReturnValueModel { Code = 200, Msg = "success", Result = "添加成功！" };
            }

            foreach (var model in modelAll)
            {
                if (model.MarketPricesModel.Where(p => p.Price > 0).Count() == 0)
                    return new ReturnValueModel { Code = 401, Msg = "鱼价信息错误!" };
                if (string.IsNullOrEmpty(model.MarketId))
                    model.MarketId = "CB8A4E64-F488-4FF2-9CC2-675697D76831";
                if (string.IsNullOrEmpty(model.FishId))
                    return new ReturnValueModel { Code = 401, Msg = "鱼种信息不能为空!" };
            }


            List<PlaceOfOriginPrice> marketPriceAll = new List<PlaceOfOriginPrice>();

            foreach (var model in modelAll)
            {
                PlaceOfOriginPrice marketPrice = new PlaceOfOriginPrice()
                {
                    Id = Guid.NewGuid().ToString(),
                    FishId = model.FishId,
                    PlaceOfOriginId = model.MarketId,
                    AveragePrice = model.MarketPricesModel.Where(a => a.Price > 0).Average(p => p.Price),
                    Remarks = model.Remarks,
                    Status = 0,
                    CreateTime = DateTime.Now,
                    CreateId = userId,
                    UserId = userId,
                    PlaceOfOriginPricesModel = model.MarketPricesModel.Where(p => p.Price > 0).Select(p => new PlaceOfOriginPrices()
                    {
                        Id = Guid.NewGuid().ToString(),
                        Price = p.Price,
                        DescriptionId = p.DescriptionId,
                        CreateTime = DateTime.Now,
                        Status = 0,
                        CreateId = userId
                    }).ToList()
                };
                marketPrice.PlaceOfOriginPricesModel.ForEach(p => p.PlaceOfOriginPriceId = marketPrice.Id);
                marketPriceAll.Add(marketPrice);
            }


            List<string> arrt = new List<string>();
            foreach (var item in marketPriceAll)
                arrt.Add(item.PlaceOfOriginId);
            string[] arrt2 = arrt.ToArray();

            var marketPriceListsql = _rep.Where<PlaceOfOriginPrice>(p => p.UserId == userId && UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(DateTime.Now), "Day") && arrt2.Contains(p.PlaceOfOriginId)).ToSql();

            var marketPriceList = _rep.Where<PlaceOfOriginPrice>(p => p.UserId == userId && UtilsHelp.Condition(Convert.ToDateTime(p.CreateTime), "Day") == UtilsHelp.Condition(Convert.ToDateTime(DateTime.Now), "Day") && arrt2.Contains(p.PlaceOfOriginId)).ToList();
            if (marketPriceList.Count() > 0)
            {
                foreach (var delectPrices in marketPriceList)
                    _rep.RemoveRange(_rep.Where<PlaceOfOriginPrices>(p => p.PlaceOfOriginPriceId == delectPrices.Id).ToList());
                _rep.RemoveRange(marketPriceList);
            }

            _rep.InsertList(marketPriceAll);

            return new ReturnValueModel { Code = 200, Msg = "success", Result = "添加成功！" };
        }
    }
}
